package com.webank.weideagroup2.chain;


import com.webank.weideagroup2.bean.Record;
import com.webank.weideagroup2.utils.Contants;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by kantlin on 2018/7/26.
 */
public class WriteAndReadBlock {

    /**
     * 写入block
     *
     * @param block
     * @throws Exception
     */
    public static void writeBlock(Block block) throws Exception {
        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(new File(Contants.FILEPATH + block.getBlockHash())));
        oos1.writeObject(block);

        ObjectOutputStream fos = new ObjectOutputStream(new FileOutputStream(Contants.FILEPATH + "lastPreviousHash"));
        fos.writeObject(block.getBlockHash());
        oos1.close();
        fos.close();
    }

    /**
     * 从block中读取
     *
     * @param vin
     * @throws Exception
     */
    public static List<Record> readBlock(String vin) throws Exception {
        List<Record> records = new ArrayList<>();
        Object hashCode;
        File file = new File(Contants.FILEPATH + "lastPreviousHash");
        if (file.exists()) {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(Contants.FILEPATH + "lastPreviousHash")));
            hashCode = in.readObject();
        } else {
            return records;
        }
        Block block = readFile(Contants.FILEPATH + hashCode.toString());

        while (block != null) {
            if (readFile(Contants.FILEPATH + block.getBlockHash()).getRecord().getVIN().equals(vin)) {
                records.add(readFile(Contants.FILEPATH + block.getBlockHash()).getRecord());
            }
            if (!block.getPreviousHash().equals("")) {
                block = readFile(Contants.FILEPATH + block.getPreviousHash());
            } else {
                return records;
            }
        }
        return records;
    }

    /**
     * 读取文件
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static Block readFile(String str) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(str)));
        Block block = (Block) ois.readObject();
        ois.close();
        return block;
    }

}
